package com.sftz.modules.minapp.activityRecord.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.sftz.assets.enums.AnswerStatusEnum;
import com.sftz.assets.enums.StateOrTimeEnum;
import com.sftz.modules.minapp.activityRecord.dto.MyteachActivityDto;
import com.sftz.modules.minapp.activityRecord.form.MyteachActivityShowForm;
import com.sftz.modules.minapp.resourceRecord.service.StudentOtherCourseScoreViewService;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

/**
 * @author   DuKL  教学活动记录
 * @Date	 2018年12月24日
 */
@IocBean
public class ActivityRecordViewService {

	@Inject
	private IDbDao dbDao;

	@Inject
	private SqlManager sqlManager;

	@Inject
	private StudentOtherCourseScoreViewService studentOtherCourseScoreViewService;

	private static final int outtime = 48;//48小时内算将过期

	private static final int willdate = 1;//将过期

	private static final int yetdate = 0;//全部

	public Object activityData(MyteachActivityShowForm myteachActivityShowForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		String token = myteachActivityShowForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		Integer courseId = myteachActivityShowForm.getCourseId();
		if (!Util.isEmpty(userId) && !Util.isEmpty(courseId)) {
			List<MyteachActivityDto> myActivity = new ArrayList<MyteachActivityDto>();
			//先查询是否有将过期的活动（若是有则默认展示将过期的）
			List<MyteachActivityDto> yetOverdue = yetOverdue(myteachActivityShowForm);
			if (!Util.isEmpty(yetOverdue)) {
				myActivity = yetOverdue;
				obj.put("activeType", willdate);
			} else {
				List<MyteachActivityDto> alreadyOverdue = alreadyOverdue(myteachActivityShowForm);
				List<MyteachActivityDto> willOverdue = willOverdue(myteachActivityShowForm);
				myActivity.addAll(alreadyOverdue);
				myActivity.addAll(willOverdue);
				obj.put("activeType", yetdate);
			}
			obj.put("myActivity", myActivity);
			return obj;
		} else {
			return null;
		}
	}

	/**
	 * @author   DuKL
	 * @Date	 2019年1月4日
	 * (effect:列表条件查询)
	 */
	public Object activityList(MyteachActivityShowForm myteachActivityShowForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		List<MyteachActivityDto> myActivity = new ArrayList<MyteachActivityDto>();
		Integer courseStatus = myteachActivityShowForm.getCourseStatus();
		if (courseStatus == StateOrTimeEnum.WILLDATED.intKey() || courseStatus == StateOrTimeEnum.DATED.intKey()) {
			myActivity = willOverdue(myteachActivityShowForm);
		} else if (courseStatus == AnswerStatusEnum.finish.intKey()
				|| courseStatus == AnswerStatusEnum.marking.intKey()) {
			myActivity = alreadyOverdue(myteachActivityShowForm);
		} else {
			List<MyteachActivityDto> alreadyOverdue = alreadyOverdue(myteachActivityShowForm);
			List<MyteachActivityDto> willOverdue = willOverdue(myteachActivityShowForm);
			myActivity.addAll(alreadyOverdue);
			myActivity.addAll(willOverdue);
		}
		Collections.sort(myActivity, new Comparator<MyteachActivityDto>() {
			@Override
			public int compare(MyteachActivityDto o1, MyteachActivityDto o2) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				try {
					if (!Util.isEmpty(o1.getEndDate()) && !Util.isEmpty(o2.getEndDate())) {
						Date dt1 = format.parse(o1.getEndDate() + "");
						Date dt2 = format.parse(o2.getEndDate() + "");
						if (dt1.getTime() > dt2.getTime()) {
							return 1;
						} else if (dt1.getTime() < dt2.getTime()) {
							return -1;
						} else {
							return 0;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		obj.put("myActivity", myActivity);
		return obj;
	}

	//查询将要过期或者已过期的教学活动
	public List<MyteachActivityDto> willOverdue(MyteachActivityShowForm myteachActivityShowForm) {
		Integer courseStatus = myteachActivityShowForm.getCourseStatus();
		List<MyteachActivityDto> myActivity = new ArrayList<MyteachActivityDto>();
		if (courseStatus == StateOrTimeEnum.WILLDATED.intKey()) {//将过期
			myActivity = yetOverdue(myteachActivityShowForm);
		} else if (courseStatus == StateOrTimeEnum.DATED.intKey()) {//已过期
			myActivity = alreadyAct(myteachActivityShowForm);
		} else {
			List<MyteachActivityDto> yetOverdue = yetOverdue(myteachActivityShowForm);
			List<MyteachActivityDto> alreadyAct = alreadyAct(myteachActivityShowForm);
			myActivity.addAll(yetOverdue);
			myActivity.addAll(alreadyAct);
		}
		return myActivity;
	}

	/**
	 * @author   DuKL
	 * @Date	 2018年12月25日
	 * (effect:将过期的活动)
	 */
	public List<MyteachActivityDto> yetOverdue(MyteachActivityShowForm myteachActivityShowForm) {
		String token = myteachActivityShowForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		List<MyteachActivityDto> myActivity = new ArrayList<MyteachActivityDto>();
		Sql datedSq = Sqls.create(sqlManager.get("minapp_teachActivity_my_center_teacherActivity_datedSq"));
		Cnd cnd = Cnd.NEW();
		datedSq.setParam("userId", userId);
		datedSq.setParam("courseId", myteachActivityShowForm.getCourseId());
		String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, outtime);
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
		SqlExpressionGroup group = new SqlExpressionGroup();
		group.andBetween("endDate", dateNow, date).orBetween("postDate", dateNow, date);
		cnd.and(group);
		datedSq.setCondition(cnd);
		myActivity = DbSqlUtil.query(dbDao, MyteachActivityDto.class, datedSq);
		for (MyteachActivityDto myteachActivityDto : myActivity) {
			myteachActivityDto.setStatus(StateOrTimeEnum.WILLDATED.intKey());
		}
		return myActivity;
	}

	/**
	 * @author   DuKL
	 * @Date	 2018年12月25日
	 * (effect:已过期)
	 */
	public List<MyteachActivityDto> alreadyAct(MyteachActivityShowForm myteachActivityShowForm) {
		String token = myteachActivityShowForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		List<MyteachActivityDto> myActivity = new ArrayList<MyteachActivityDto>();
		Sql datedSq = Sqls.create(sqlManager.get("minapp_teachActivity_my_center_teacherActivity_datedSq"));
		Cnd cnd = Cnd.NEW();
		datedSq.setParam("userId", userId);
		datedSq.setParam("courseId", myteachActivityShowForm.getCourseId());
		String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		cnd.and("endDate", "<", dateNow);
		datedSq.setCondition(cnd);
		myActivity = DbSqlUtil.query(dbDao, MyteachActivityDto.class, datedSq);
		for (MyteachActivityDto myteachActivityDto : myActivity) {
			myteachActivityDto.setStatus(StateOrTimeEnum.DATED.intKey());
		}
		return myActivity;
	}

	//查询已审批或未审批的教学活动
	public List<MyteachActivityDto> alreadyOverdue(MyteachActivityShowForm myteachActivityShowForm) {
		String token = myteachActivityShowForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		List<MyteachActivityDto> myActivity = new ArrayList<MyteachActivityDto>();
		Sql studentS = Sqls.create(sqlManager.get("minapp_teachActivity_my_center_teacherActivity_list"));
		Cnd cnd = Cnd.NEW();
		if (myteachActivityShowForm.getCourseStatus() == AnswerStatusEnum.finish.intKey()) {
			cnd.and("tap.status", "!=", AnswerStatusEnum.marking.intKey());
		} else if (myteachActivityShowForm.getCourseStatus() == AnswerStatusEnum.marking.intKey()) {
			cnd.and("tap.status", "=", AnswerStatusEnum.marking.intKey());
		} else {
			SqlExpressionGroup group2 = new SqlExpressionGroup();
			group2.and("tap.status", "=", AnswerStatusEnum.finish.intKey())
					.or("tap.status", "=", AnswerStatusEnum.marking.intKey()).or("tap.status", "=", -1);
			cnd.and(group2);
		}
		cnd.and("tw.userId", "=", userId).and("c.id", "=", myteachActivityShowForm.getCourseId());
		studentS.setCondition(cnd);
		myActivity = DbSqlUtil.query(dbDao, MyteachActivityDto.class, studentS);
		return myActivity;
	}

}
